﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using System.IO;

namespace RefinementHost
{
    public partial class RefinementUC : UserControl
    {
        public RefinementUC()
        {
            InitializeComponent();
        }

        private void buttonConceptFileBrowse_Click(object sender, EventArgs e)
        {
            openFileDialog_LoadPlugin.Multiselect = false;
            openFileDialog_LoadPlugin.FileName = string.Empty;
            //openFileDialog_LoadPlugin.Filter = "Plugin (*.dll) |*.dll";
            if (openFileDialog_LoadPlugin.ShowDialog() == DialogResult.OK)
            {
                this.textBoxConceptFilePath.Text = openFileDialog_LoadPlugin.FileName;
                Global.conceptList = Concept.FromConceptFile(this.textBoxConceptFilePath.Text);
            }
        }

        private void buttonRunRefinement_Click(object sender, EventArgs e)
        {
            this.treeViewRelationship.Nodes.Clear();
            List<Relationship> relationshipList = new List<Relationship>();
            Dictionary<int, int> WebpageID_ConceptID_Dict = Concept.ConceptToWebpageConceptDict(Global.conceptList);

            #region Relationship Discovery
            foreach (Concept curConcept in Global.conceptList)
            {
                foreach (Vector curVector in curConcept.WebpageInstanceVector)
                {
                    List<Link> curInstanceLinkList = DAL.WebpageDAL.GetLinks(curVector.WebpageID);
                    int concept1ID = WebpageID_ConceptID_Dict[curVector.WebpageID];
                    foreach (Link curLink in curInstanceLinkList)
                    {
                        if (curLink.SourceWebpageID != curLink.DestWebpageID)
                        {
                            if (WebpageID_ConceptID_Dict.ContainsKey(curLink.DestWebpageID))
                            {
                                int concept2ID = WebpageID_ConceptID_Dict[curLink.DestWebpageID];

                                if (concept1ID != concept2ID)
                                {
                                    int index = Relationship.FindRelationship(relationshipList, concept1ID, concept2ID);
                                    // if this relationship exists
                                    if (index != -1)
                                    {
                                        relationshipList[index].Score++;
                                        if (Relationship.IsLinkExisting(relationshipList[index].LinkList, curLink.SourceWebpageID, curLink.DestWebpageID) == false)
                                        {
                                            relationshipList[index].LinkList.Add(new Link(curLink.SourceWebpageID, curLink.DestWebpageID));
                                        }
                                    }
                                    else
                                    {
                                        Relationship curRelationship = new Relationship();
                                        curRelationship.Concept1ID = concept1ID;
                                        curRelationship.Concept2ID = concept2ID;
                                        curRelationship.Score = 1;
                                        curRelationship.LinkList.Add(new Link(curLink.SourceWebpageID, curLink.DestWebpageID));
                                        relationshipList.Add(curRelationship);
                                    } 
                                }
                            } 
                        }
                    }
                }
            }
            Global.relationshipList = relationshipList;
            #endregion

            #region Add relationship to TreeView
            List<Webpage> allWebpages = DAL.WebpageDAL.GetWebpages();
            Dictionary<int, Webpage> allWebpagesDict = DTO.Webpage.WebpagesToDict(allWebpages);

            foreach (Relationship curRelationship in relationshipList)
            {
                TreeNode curNode = new TreeNode("Relationship [" + curRelationship.Concept1ID + "] -> [" + curRelationship.Concept2ID + "] [Score: " + curRelationship.Score + " ]");
                foreach (Link curLink in curRelationship.LinkList)
                {
                    TreeNode curLinkNode = new TreeNode("[" + curLink.SourceWebpageID + "] -> [" + curLink.DestWebpageID + "]");
                    Webpage sourceWP = allWebpagesDict[curLink.SourceWebpageID];
                    Webpage destWP = allWebpagesDict[curLink.DestWebpageID];
                    curLinkNode.Nodes.Add("(" + sourceWP.ID + ") [ " + sourceWP.Title + " ] [ " + sourceWP.URL + " ]");
                    curLinkNode.Nodes.Add("(" + destWP.ID + ") [ " + destWP.Title + " ] [ " + destWP.URL + " ]");
                    curNode.Nodes.Add(curLinkNode);
                }
                this.treeViewRelationship.Nodes.Add(curNode);
            }

            Global.relationshipList = relationshipList;
            #endregion

            #region Visualization
            string graphInDotFormatStr = string.Empty;

            graphInDotFormatStr = Relationship.RelationshipToGraphInDotFormat(relationshipList, Directory.GetCurrentDirectory() + @"\graph.dot");
            /*
            FileStream fs = new FileStream(graphInDotFormatPath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string graphInDotFormatStr = sr.ReadToEnd();
            sr.Close();
            fs.Close();
            */
            try
            {
                kpOntologyViewer.Image = new Bitmap(Utilities.GraphViz.RenderImage(graphInDotFormatStr, "dot", "png"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error!");
            }
            #endregion
        }

        private void buttonVectorFileBrowse_Click(object sender, EventArgs e)
        {
            openFileDialog_LoadPlugin.Multiselect = false;
            openFileDialog_LoadPlugin.FileName = string.Empty;
            //openFileDialog_LoadPlugin.Filter = "Plugin (*.dll) |*.dll";
            if (openFileDialog_LoadPlugin.ShowDialog() == DialogResult.OK)
            {
                this.textBoxVectorFilePath.Text = openFileDialog_LoadPlugin.FileName;
                Global.vectorList = Vector.FromVectorFile(openFileDialog_LoadPlugin.FileName);
            }
        }

        private void buttonExport2XML_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog myFolderBrowseDlg = new FolderBrowserDialog();
            myFolderBrowseDlg.Description = "Choose the directory that will contain the exported xml file.";
            if (myFolderBrowseDlg.ShowDialog() == DialogResult.OK)
            {
                string filePath = myFolderBrowseDlg.SelectedPath;
                filePath += @"\" + "relationship_" + DateTime.Now.ToString("MMM-d-yyyy HH-mm-ss") + ".xml";
                Relationship.ToRelationshipFile(Global.relationshipList, filePath);
            }
        }

    }
}
